# coding=utf-8

from __future__ import print_function
from collections import OrderedDict
import logging, os, commands, socket
from app.extensions import log

class VPlatform(object):

    def __init__(self):
        log.info('=================init VPlatform====================')

    def hostname(self):
        return commands.getoutput('hostname')

    def ipaddress(self):
        try:
            csock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            csock.connect(('8.8.8.8', 80))
            (addr, port) = csock.getsockname()
            csock.close()
            return addr
        except socket.error:
            return '127.0.0.1'

    def meminfo(self):

        ''' Return the information in /proc/meminfo as a dictionary'''
        meminfo = OrderedDict()

        with open('/proc/meminfo') as f:
            for line in f:
                # log.info('=================%s', line)
                meminfo[line.split(':')[0]] = line.split(':')[1].strip()

            f.close()
        return meminfo

    def disk_stat(self, path):
        hd = {}
        disk = os.statvfs(path)
        log.info('=================statvfs:%s', disk)
        hd['free'] = (disk.f_bsize * disk.f_bavail) / 1024.0 / 1024
        hd['total'] = (disk.f_bsize * disk.f_blocks) / 1024.0 / 1024
        hd['used'] = (disk.f_bsize * (disk.f_blocks - disk.f_bfree)) / 1024.0 / 1024
        return hd

    def disk_free(self):
        deskfree = commands.getoutput('df -Ph')
        lines = deskfree.split('\n')
        # lines.pop(0)
        return lines

    def cpu_stat(self):
        cpu = []
        cpuinfo = {}

        with open('/proc/cpuinfo') as f:
            for line in f:
                # log.info('=================cpuinfo:%s', line)
                if line == '\n':
                    cpu.append(cpuinfo)
                    cpuinfo = {}

                if len(line) < 2:
                    continue

                cpuinfo[line.split(':')[0].rstrip()] = line.split(':')[1].rstrip()
            f.close()

        return cpu

    def cpu_free(self):
        cpufree = commands.getoutput("source /etc/profile && top -bn2 |grep -w Cpu|awk 'NR==2{print $5}'").replace('%id,', '')
        return '%s' % cpufree

    def cpu_stat_cores(self):

        processers = 0
        cores = 0

        cpustat = self.cpu_stat()
        for cpu in cpustat:
            processers += 1
            cores += int(cpu['cpu cores'])

        return str(processers) + '(' + str(cores) + ')'
